$(function () {
    application.initPagePosition(['管理中心', '我的服务', '管理服务', '修改服务'], '管理服务');

    serviceEdit = new ServiceEdit();
    serviceEdit.layerLoadingIdx = layer.load(0, {shade: false});
});
var serviceEdit;

var ServiceEdit = function () {
    this.init();
};
ServiceEdit.prototype = {
    $categoryOne: $('#service_one'), //一级分类
    $categoryTwo: $('#service_two'), //二级分类
    $categoryThree: $('#service_three'), //三级分类
    contentEditor: null,
    goodsId: Number($('[name=goodsId]').val()), //服务ID
    weekMapper: {
        1: '星期一',
        2: '星期二',
        3: '星期三',
        4: '星期四',
        5: '星期五',
        6: '星期六',
        0: '星期日',
    },
    init: function () {
        var that = this;

        // 一级服务分类
        that.$categoryOne.on('change', function (event, callback) {
            var $this = $(this);
            var value = $this.val();
            that.$categoryTwo.empty().append('<option value="">请选择二级服务分类</option>');
            that.$categoryThree.empty().append('<option value="">请选择三级服务分类</option>');
            that.queryCategoryAjax(Number(value), function (items) {
                var $el = _.templateResolve('<option value="{{=categoryId}}">{{=categoryType}}</option>', items);
                that.$categoryTwo.empty().append('<option value="">请选择二级服务分类</option>').append($el);
                callback && callback();
            });
        });
        // 二级服务分类
        that.$categoryTwo.on('change', function () {
            var $this = $(this);
            var value = $this.val();
            if ($.trim(value) == '') {
                that.$categoryThree.empty().append('<option value="">请选择三级服务分类</option>');
                return;
            }
            that.queryCategoryAjax(Number(value), function (items) {
                var $el = _.templateResolve('<option value="{{=categoryId}}">{{=categoryType}}</option>', items);
                that.$categoryThree.empty().append('<option value="">请选择三级服务分类</option>').append($el);
            });
        });

        //选择服务方式
        $('#service_form_box ul li.ways_li em').on('click', function () {
            var $this = $(this);
            $this.addClass('hover').siblings().removeClass('hover');
            $this.parent().find('[name=service_ways]').val($this.attr('way'));
        });

        // 图片上传
        //上传服务标题图 浮动效果.
        $('#upload_thumb').on('mouseenter mouseleave', function () {
            $(this).siblings('#upload_btn').toggleClass('hover');
        });
        that.goodsImageUpload();

        //删除上传的服务标题图
        $(document).on('click', '#form_imglsit .icon_delete', function () {
            var objClick = $(this);
            var _layerId = layer.confirm('确认删除该图？', {
                btn: ['确认', '再考虑下'], //按钮
                title: '温馨提示',
                icon: 0
            }, function () {
                objClick.parent('a').remove();
                layer.close(_layerId);
            }, function () {
                //layer.msg('多谢手下留情！',{icon:6,time:1000});
            });
        });

        // 服务标签
        //添加标签
        $('#label_btn').on('click', function () {
            var $this = $(this);
            var $tag = $('#label');
            if ($.trim($tag.val()) == '') {
                that.tipsMsg({el: $this, msg: '请输入标签名称!', isShow: true});
                return;
            }
            //单个标签字符长度判断
            var tagNames = $.trim($tag.val()).replace(/，/g, ',').split(',');
            if ($(tagNames).filter(function () {
                    return this.length > 20;
                }).get().length > 0) {
                that.tipsMsg({el: $this, msg: '单个标签字符不得超过20个字符!', isShow: true});
                return;
            }
            //重复便签判断
            var exist = $(tagNames).filter(function () {
                var tagName = this;
                return $('#form_label span .icon_footer').filter(function () {
                        return $(this).text() == tagName
                    }).length > 0;
            }).get();
            if (exist.length > 0) {
                that.tipsMsg({el: $this, msg: '存在重复标签: [' + exist.join(',') + ']', isShow: true});
                return;
            }
            var _html = [];
            $.each(tagNames, function () {
                _html.push('<span class="clearfix underscore-template-rendered"><i class="icon_member icon_header"></i><i class="icon_footer">' + this + '</i><i class="icon_delete">x</i></span>');
            });
            $('#form_label').append(_html.join(''));
            layer.msg('添加成功!')
            $tag.val('');
        });
        //删除服务标签
        $('body').on('click', '#form_label .icon_delete', function () {
            var $this = $(this);
            var index1 = layer.confirm('确认删除该标签？', {
                btn: ['确认', '再考虑下'], //按钮
                title: '温馨提示',
                icon: 0
            }, function () {
                layer.close(index1);
                $this.parent('span').remove();
            }, function () {
                //layer.msg('多谢手下留情！',{icon:6,time:1000});
            });
        });

        //加载服务时间段数据, 并渲染
        this.initServerRangeTime();

        //提交表单
        $('#form_submit').on('click', function () {
            var status = $(this).data('status');
            if (that.validateForm()) {
                layer.confirm('确认发布服务？', {
                    btn: ['确认', '再考虑下'], //按钮
                    title: '温馨提示',
                    icon: 0
                }, function () {
                    that.submitForm(status, function (data) {
                        layer.msg((status == 1 ? '提交审核成功!' : '保存至草稿成功!') + ' 5 秒后调整至服务管理.');
                        setTimeout(function () {
                            window.location.href = window['ctx'] + '/member/service/manage';
                        }, 5000);
                    });
                });
            }
        });

        //加载服务信息
        that.queryGoodsById(function (data) {
            that.bindGoodsData(data);
        });

        return that;
    },
    /**
     * 绑定服务数据渲染
     * @param data 服务数据
     */
    bindGoodsData: function (data) {
        var that = this;
        $('#title').val(data['goodsName']);
        $('#price').val(data['marketPrice']);
        $('#unit').val(data['goodsCompanyNote']);
        //服务时间
        var serviceTimeRangeVal = $(data['goodsServerTimeList']).map(function () {
            return this['week'] + '-' + this['timeRange'];
        }).get().join(',');
        $('#serviceTimeRange').val(serviceTimeRangeVal); //保存请求值
        var serviceTimeRangeMap = _.groupBy(data['goodsServerTimeList'], 'week');
        var serviceTimeRangeShowVal = [];
        $.each(serviceTimeRangeMap, function (key, value) {
            var weekStr = that.weekMapper[key];
            if ($.trim(weekStr) == '') return;
            serviceTimeRangeShowVal.push(weekStr + '(' + $(value).map(function () {
                    return Constants.goodsServerTimeDefine[this['timeRange']];
                }).get().join(',') + ')');
        });
        $('#service_time').val(serviceTimeRangeShowVal.join(',')).attr('title', serviceTimeRangeShowVal.join(',')); //仅显示值
        //服务方式
        $('#ways_li em').filter(function () {
            return Number($(this).attr('way')) == data.serverType
        }).addClass('hover').siblings().removeClass('hover');
        $('[name=service_ways]').val(data.serverType);
        //头像
        $('.form_imglsit').empty().append(_.templateResolve('<a><img src="{{=uri}}" src-default="{{=window.ctx}}/assets/images/default_content.png" alt="" /><i class="icon_delete">x</i></a>', data['imageItemList']));
        application.loadDefaultImgOnError($('.form_imglsit'));
        //具体内容
        //  富文本加载
        //标签
        $('#form_label').empty().append(_.templateResolve('<span class="clearfix"><i class="icon_member icon_header"></i><i class="icon_footer">{{=tagName}}</i><i class="icon_delete">x</i></span>', data['tagList']))
        $('#content').html(data.article ? data.article.content : '');
        that.contentEditor = UE.getEditor('content');

        // 绑定分类数据, 一级,二级
        that.initOneLevelCategory(function () {
            if (data.categories && data.categories.length == 0) {
                return;
            }
            that.$categoryOne.val(data.categories[0]['categoryId']);
            that.$categoryOne.trigger('change', function () {
                that.$categoryTwo.val(data.categories[1]['categoryId']);
            });
        });

        //处理完毕显示页面
        layer.close(that.layerLoadingIdx);
        $('.container_right').removeAttr('style');
    },
    /**
     * 提交表单
     * @param status 提交审核, 还是草稿
     * @param callback 回调函数
     */
    submitForm: function (status, callback) {
        var that = this;
        var params = {
            goodsId: that.goodsId,
            title: $.trim($('#title').val()),
            categoryId: Number(that.$categoryTwo.val()),
            price: Number($.trim($('#price').val())),
            priceUnit: $.trim($('#unit').val()),
            date1: $('#serviceTimeRange').val(),
            date2: '',
            serverType: Number($('#service_ways').val()),
            images: $('#form_imglsit img').map(function () {
                return $(this).attr('src');
            }).get().join(','),
            tags: $('#form_label span .icon_footer').map(function () {
                return $(this).text()
            }).get().join(','),
            content: that.contentEditor.getContent(),
            cases: '',
            status: Number(status)
        };
        console.log(params);
        $.ajax({
            url: window['ctx'] + '/member/service/update.json',
            type: 'post',
            dataType: 'json',
            loading: false, //禁用 loading动画效果
            data: {
                json: JSON.stringify(params)
            },
        }).done(function (data) {
            if (!data.success) {
                return;
            }
            callback && callback(data.result);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('网络繁忙, 保存失败, 请稍后再试!', {icon: 2});
        })
    },
    /**
     * 提交数据进行数据验证
     * @returns {boolean} 验证是否成功
     */
    validateForm: function () {
        var that = this;
        //去除前后空格
        $('input').each(function () {
            var $this = $(this);
            $this.val($.trim($this.val()));
        });
        //标题
        var $title = $('#title');
        if ($title.val() == '' || $title.val().length > Number($title.attr('maxlength'))) {
            that.tipsMsg({el: $title, msg: $title.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }
        //分类
        var $category = $('#service_two');
        if ($category.val() == '') {
            that.tipsMsg({el: $category, msg: $category.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }

        //价格
        var $price = $('#price');
        if ($price.val() == '' || $price.val().length > Number($price.attr('maxlength')) || isNaN($price.val())) {
            that.tipsMsg({el: $price, msg: $price.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }
        //价格单位
        var $priceUnit = $('#unit');
        if ($priceUnit.val() == '' || $priceUnit.val().length > Number($priceUnit.attr('maxlength'))) {
            that.tipsMsg({el: $priceUnit, msg: $priceUnit.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }
        //服务时间
        var $serviceTime = $('#service_time');
        var $serviceTimeRange = $('#serviceTimeRange');
        if ($serviceTime.val() == '' || $serviceTimeRange.val() == '') {
            that.tipsMsg({el: $serviceTime, msg: $serviceTime.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }
        //服务方式
        var $serviceWays = $('#service_ways');
        if ($serviceWays.val() == '') {
            that.tipsMsg({el: $serviceWays, msg: $serviceWays.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }
        //服务标题图
        var $formImglsit = $('.form_imglsit');
        var $uploadThumb = $('#upload_thumb');
        if ($formImglsit.find('img').length == 0 || $formImglsit.find('img') > 5) {
            that.tipsMsg({el: $uploadThumb, msg: $uploadThumb.attr('message'), isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }
        //具体内容
        var content = that.contentEditor.getContent();
        if (content == '' || content.replace(/\s/g, "") == '<p><br/></p>' || content.replace(/\s/g, "") == '<p></p>') {
            that.tipsMsg({el: $('#content'), msg: '请填写具体内容!', isShow: true});
            return false;
        } else {
            that.tipsMsg({isShow: false});
        }

        return true;
    },
    /**
     * tips 提示信息, 用于表单的显示
     * @param $obj 提示定位对象
     * @param msg 提示信息
     * @param valid 是否验证
     */
    tipsMsg: function (options) {
        //if (options.el) options.el[options.isShow ? 'addClass' : 'removeClass']('error_border');
        if (options.isShow) {
            $('html, body').animate({scrollTop: options.el.offset().top - 200}, 500);
            layer.tips(options.msg, options.el, {tips: [2, '#FF7800'], zIndex: 9999});
        } else {
            layer.closeAll('tips');
        }
    },
    /**
     * 默认加载一级分类
     */
    initOneLevelCategory: function (callback) {
        var that = this;
        that.queryCategoryAjax(0, function (items) {
            var $el = _.templateResolve('<option value="{{=categoryId}}">{{=categoryType}}</option>', items);
            that.$categoryOne.append($el);
            callback && callback();
        });
    },
    /**
     * 根据分类父级ID查询分类
     * @param categoryParentId 分类父级ID
     * @param callback 回调
     */
    queryCategoryAjax: function (categoryParentId, callback) {
        $.ajax({
            url: window['ctx'] + '/service/category/list.json',
            type: 'get',
            dataType: 'json',
            loading: false, //禁用 loading动画效果
            data: {
                categoryParentId: categoryParentId
            }
        }).done(function (data) {
            if (!data.success) {
                return;
            }
            callback && callback(data.result);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('网络繁忙, 查询分类信息失败, 请稍后再试!', {icon: 2});
        })
    },
    /**
     * 服务标题图上传
     */
    goodsImageUpload: function () {
        var that = this;
        var $formImglist = $('#form_imglsit');
        $('#upload_thumb').fileupload({
            url: window['ctx'] + '/common/fileupload/tmp.json',
            dataType: 'json',
            add: function (e, data) {
                //文件过滤
                //判断所选文件个数
                var $uploadedImage = $formImglist.find('img');
                if (data && data.originalFiles && data.originalFiles.length > (5 - $uploadedImage.length)) {
                    layer.alert('标题图片不能超过5张，还可上传' + (5 - $uploadedImage.length) + '张。', {
                        icon: 0,
                        skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
                    });
                    return;
                }

                //判断所选文件格式，根据后缀名
                for (var i = 0; i < data.originalFiles.length; i++) {
                    var fileItem = data.originalFiles[i];
                    var fileName = fileItem.name.toUpperCase();
                    if (fileName.lastIndexOf('JPG') == -1 && fileName.lastIndexOf('PNG') == -1 && fileName.lastIndexOf('GIF') == -1) {
                        layer.alert('所选图片格式必须为 gif/jpg/png !', {
                            icon: 0,
                            skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
                        });
                        return;
                    }
                    if (fileItem.size > 3000000) {
                        layer.alert('图片大小不能超过3兆,请压缩图片后再上传!', {
                            icon: 0,
                            skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
                        });
                        return;
                    }
                }
                if (e.isDefaultPrevented()) {
                    return;
                }
                if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) {
                    data.process().done(function () {
                        data.submit();
                    });
                }
            },
            done: function (e, data) {
                var templateContent = '<a title="{{=originalFilename}}"> \
                    <img src="{{=url}}" alt="{{=originalFilename}}" src-default="{{=window.ctx}}/assets/images/default_content.png"> \
                        <i class="icon_delete" title="移除此图">x</i> \
                    </a>';
                var $html = _.templateResolve(templateContent, data.result.result[0]);

                setTimeout(function () {
                    $formImglist.append($html);
                    application.loadDefaultImgOnError($('.form_imglsit'));
                }, 500);
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');

    },
    /**
     * 根据后台定义, 渲染时间段选择, 以及事件绑定
     */
    initServerRangeTime: function () {
        var that = this;
        var $container = $('ul.date_content');
        for (var i = 1; i <= 7; i++) {
            var week = i == 7 ? 0 : i;
            var _html = [];
            $.each(Constants.goodsServerTimeDefine, function (idx, rangeDesc) {
                _html.push("<span data-week=" + week + " data-idx=" + idx + ">" + rangeDesc + "</span>");
            })
            $container.append('<li data-week=' + week + '>' + _html.join('') + '</li>')
        }
        //---------
        var modalIdx;
        //选择服务时间段
        $container.find('li span').on('click', function () {
            $(this).toggleClass('hover');
        });
        //提交服务时间段
        $('#date_submit_btn').on('click', function () {
            modalIdx && layer.close(modalIdx);
            //仅用于显示
            var showVal = $('.date_content li').filter(function () {
                return $(this).find('span.hover').length > 0;
            }).map(function () {
                var $this = $(this);
                var week = that.weekMapper[Number($this.data('week'))];
                var timeRanges = $(this).find('span').filter(function () {
                    return $(this).hasClass('hover');
                }).map(function () {
                    return $(this).text();
                }).get().join(',');
                return timeRanges != '' ? week + '(' + timeRanges + ')' : '';
            }).get().join(',');
            $('#service_time').val(showVal).attr('title', showVal);

            //参数参数值
            var val = $('.date_content span').filter(function () {
                return $(this).hasClass('hover');
            }).map(function () {
                return $(this).data('week') + '-' + $(this).data('idx');
            }).get().join(',');
            $('#serviceTimeRange').val(val);
        });
        //选择服务时间
        $('#service_time').on('click', function () {
            var serviceTimeRange = $('#serviceTimeRange').val();
            var items = $('#module_date_box span').removeClass('hover');
            $(serviceTimeRange.split(',')).each(function () {
                var week = Number(this.split('-')[0]);
                var idx = Number(this.split('-')[1]);
                items.filter(function () {
                    var $this = $(this);
                    return Number($this.data('week')) == week && Number($this.data('idx')) == idx;
                }).addClass('hover');
            });
            modalIdx = layer.open({
                type: 1,
                title: '请选择日期',
                shadeClose: true,
                shade: 0.5,
                closeBtn: 1,
                maxmin: false, //开启最大化最小化按钮
                area: ['600px', '380px'],
                content: $('#module_date_box')
            });
        });
    },
    /**
     * 根据服务ID查询服务
     * @param goodsId 服务ID
     * @param callback 回调
     */
    queryGoodsById: function (callback) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/member/service/goods_by_id.json',
            type: 'get',
            dataType: 'json',
            loading: false,
            data: {
                goodsId: that.goodsId
            }
        }).done(function (data) {
            if (data.success) {
                callback && callback(data.result);
            } else {
                layer.msg('网络繁忙, 没有查询到服务信息, 请稍后再试!', {icon: 2});
            }
        });
    }
};